package com.xiaoyao.common.pojo;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

@Data
@Entity
public class User implements UserDetails {

    private Long id;

    private String username;

    private String password;

    private String role;

    private String status;

    @Transient
    private Collection<GrantedAuthority> grantedAuthorities;

    public static User of(String username){
        User user = new User();
        user.setUsername(username);
        return user;
    }

    public static User of(String username, String password, Collection<GrantedAuthority> grantedAuthorities){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setGrantedAuthorities(grantedAuthorities);
        return user;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Id
    public Long getId() {
        return id;
    }

    @Transient
    private Collection<? extends GrantedAuthority> getGrantedAuthorities() {
        return getAuthorities();
    }

    @JsonIgnore
    @Transient
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Optional.ofNullable(this.role).map(p -> List.of(new SimpleGrantedAuthority(p))).orElse(null);
    }

    @JsonIgnore
    @Transient
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Transient
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Transient
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonIgnore
    @Transient
    @Override
    public boolean isEnabled() {
        return true;
    }
}
